#include "../third_party/httplib.h"
#include "../third_party/json.hpp"
#include "bundle.h"
#include <fstream>
#include <iostream>
#include <vector>
#include <filesystem>
using json = nlohmann::json;
using namespace httplib;
namespace fs = std::filesystem;

// 断点续传上传
void upload_file(const std::string& filename, const std::string& server_addr) {
    Client cli(server_addr.c_str());
    // 查询断点
    auto res = cli.Get( ("/progress?filename=" + filename).c_str() );
    size_t offset = 0;
    if(res && res->status == 200) {
        json j = json::parse(res->body);
        offset = j["offset"];
    }
    std::ifstream ifs(filename, std::ios::binary);
    ifs.seekg(offset);
    std::string data((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
    httplib::Params params = { {"filename", filename}, {"offset", std::to_string(offset)} };
    cli.Post("/upload", params, data, "application/octet-stream");
}

// 下载文件
void download_file(const std::string& filename, const std::string& server_addr) {
    Client cli(server_addr.c_str());
    auto res = cli.Get( ("/download?filename=" + filename).c_str() );
    if(res && res->status == 200) {
        std::ofstream ofs(filename, std::ios::binary);
        ofs.write(res->body.c_str(), res->body.size());
    }
}

// 查询热点文件
void query_hot(const std::string& server_addr) {
    Client cli(server_addr.c_str());
    auto res = cli.Get("/hot");
    if(res && res->status == 200) {
        json j = json::parse(res->body);
        std::cout << "热点文件: ";
        for(auto& f : j) std::cout << f << " ";
        std::cout << std::endl;
    }
}

int main() {
    // 示例：打包、上传、下载、查询热点
    std::vector<std::string> files = {"test1.txt", "test2.txt"};
    bundle_files(files, "bundle.dat");
    upload_file("bundle.dat", "localhost:8080");
    download_file("bundle.dat", "localhost:8080");
    query_hot("localhost:8080");
    return 0;
} 